﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace WeiTao.Controllers
{
    public class TopController : Controller
    {
        private string client_id = "21441486";
        private string client_secret = "f3d023d8d29d550948a0b0a38f2b972d";
        private string redirect_uri = "http://weitao.azurewebsites.net/top/callback";
        //private string redirect_uri = "http://127.0.0.1:18368/top/callback";

        public ActionResult SignIn()
        {
            string url = string.Format("{0}?client_id={1}&response_type={2}&redirect_uri={3}", "https://oauth.taobao.com/authorize", client_id, "code", redirect_uri);        
            return Redirect(url);
        }

        public async Task<ActionResult> CallBack(string code, string state)
        {
            //利用code去获取令牌信息得到当前登录用户的淘宝昵称
            //然后将昵称和code写入队列，排队来执行同步数据的任务
            using (var http = new HttpClient())
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                    {"grant_type", "authorization_code"},
                    {"code", code},
                    {"redirect_uri", redirect_uri}
                });

                //await异步等待回应
                var response = await http.PostAsync("https://oauth.taobao.com/token", content);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //await异步读取最后的JSON（注意此时gzip已经被自动解压缩了，因为上面的AutomaticDecompression = DecompressionMethods.GZip）
                var result = await response.Content.ReadAsStringAsync();
                string nick = JObject.Parse(result)["taobao_user_nick"].ToString();
                //获取了昵称，把昵称和code保存到数据库。另外background自动运行任务。
                this.ViewBag.TaobaoUserNick = nick;
            }
            return View("Index");
        }
    }
}
